package com.simplefaith.delisty.component;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup.LayoutParams;

public class TiledAnimationWidget extends View {

	private Rect sourceRect, destRect;
	private Bitmap bitmap;
	private BitmapDrawable drawable;

	private int tiledIndexX, tiledIndexY;

	private int bmpW, bmpH;

	private Handler animationTiledHandler = new Handler();

	private final Runnable animatedRun = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			NextTile();
			animationTiledHandler.postDelayed(this, 30);
		}

	};

	/**
	 * @param context
	 *            : context of activity
	 * @param drawable
	 *            ID : image drawable id
	 * @param tiledX
	 *            : tiled of X
	 * @param tiledY
	 *            : tiled of Y
	 * @param position
	 *            : sprite position
	 * @param size
	 *            : sprite size
	 * **/
	public TiledAnimationWidget(Context context, int drawableRid, int tiledX,
			int tiledY, Point position, Point size) {
		super(context);
		Activity activity = (Activity) context;
		destRect = new Rect(position.x, position.y, position.x + size.x,
				position.y + size.y);
		bitmap = BitmapFactory.decodeResource(context.getResources(),
				drawableRid);
		drawable = new BitmapDrawable(context.getResources(), bitmap);
		drawable.setTileModeXY(TileMode.CLAMP, TileMode.CLAMP);

		bmpW = bitmap.getWidth() / tiledX;
		bmpH = bitmap.getHeight() / tiledY;

		//
		activity.addContentView(this, new LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

		// Start Anim
		animationTiledHandler.postDelayed(animatedRun, 60);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);

		canvas.drawBitmap(bitmap, sourceRect, destRect, null);

	}

	private void NextTile() {
		tiledIndexX++;
		if (tiledIndexX > 3) {
			tiledIndexX = 0;
			tiledIndexY++;
		}
		if (tiledIndexY > 1) {
			tiledIndexY = 0;
			tiledIndexX = 0;
		}
		sourceRect = new Rect(tiledIndexX * bmpW, tiledIndexY * bmpH,
				(tiledIndexX + 1) * bmpW, (tiledIndexY + 1) * bmpH);
		invalidate();
	}
	
	public void finalize(){
		try {
			super.finalize();			
			animationTiledHandler.removeCallbacks(animatedRun);
			bitmap.recycle();
		} catch (Throwable e) {
			
			e.printStackTrace();
		}		
	}

}
